package com.huobao.yunying.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.huobao.yunying.activitys.Act_Jiesuan;
import com.huobao.yunying.activitys.Act_Kefu;
import com.huobao.yunying.adapters.Adapter_Gouwuche;
import com.huobao.yunying.adapters.Adapter_Tuijians;
import com.huobao.yunying.entity.Detailprice_intervals;
import com.huobao.yunying.entity.GouwucgeGoods;
import com.huobao.yunying.entity.GouwucheList;
import com.huobao.yunying.entity.Gouwuche_spec;
import com.huobao.yunying.entity.Gouwuche_specification;
import com.huobao.yunying.entity.TuijianGoods;
import com.huobao.yunying.https.Http;
import com.huobao.yunying.https.HttpConst;
import com.huobao.yunying.https.HttpListener;
import com.huobao.yunying.https.HttpUtil;
import com.huobao.yunying.huanxin.ui.ui.LoginActivity;
import com.huobao.yunying.utils.SessionUtils;
import com.huobao.yunying.utils.SkipUtils;
import com.huobao.yunying.utils.Utils;
import com.huobao.yunying.views.NoScrollGridView;
import com.huobao.zhangying.R;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class Fragment_Gouwuche extends Fragment
		implements OnGroupClickListener, OnChildClickListener, OnCheckedChangeListener, OnClickListener {
	private View emptyView;
	private NoScrollGridView gridview;
	private Adapter_Tuijians adapter_empty;
	private Adapter_Gouwuche m_Gouwuche_Adapter;
	private ExpandableListView listview;
	private ImageView btn_back;
	private TextView tv_title;
	/** 总选择 */
	private CheckBox checkbox;
	/** 总价格 */
	private TextView tv_price;
	private View llyt_bottom;

	// 结算按钮
	private TextView btn_jiesuan;

	private boolean isFromActivity;

	private TextView tv_kefu;

	public Fragment_Gouwuche() {
		isFromActivity = false;
	}


	public static Fragment_Gouwuche getInstant(boolean isFromActivity){
		Fragment_Gouwuche instance = new Fragment_Gouwuche();
		Bundle args = new Bundle();
		args.putBoolean("isFromActivity", isFromActivity);
		instance.setArguments(args);
		return instance;
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.layout_gouwuche, null);
//		this.isFromActivity = getArguments().getBoolean("isFromActivity");
		btn_back = (ImageView) view.findViewById(R.id.btn_back);
		btn_jiesuan = (TextView) view.findViewById(R.id.btn_jiesuan);
		tv_title = (TextView) view.findViewById(R.id.tv_title);
		checkbox = (CheckBox) view.findViewById(R.id.checkbox);
		tv_price = (TextView) view.findViewById(R.id.tv_price);
		tv_kefu = (TextView) view.findViewById(R.id.tv_kefu);
		llyt_bottom = view.findViewById(R.id.llyt_bottom);
		checkbox.setOnCheckedChangeListener(this);
		initTitleBar();
		initEmptyView(view);
		listview = (ExpandableListView) view.findViewById(R.id.listview);
		listview.setOnChildClickListener(this);
		listview.setOnGroupClickListener(this);
		EventBus.getDefault().register(this);
		btn_jiesuan.setOnClickListener(this);
		tv_kefu.setOnClickListener(this);
		if (isFromActivity) {
			init(true);
		}
		return view;
	}
	@Subscriber(tag = "refreshGouwche")
	public void refreshGouwche(String s){
		getGouwucgeData();
	}

	public void setIsFrom() {
		this.isFromActivity = true;
		init(true);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		EventBus.getDefault().unregister(this);
	}

	@Subscriber(tag = "editGouwucheSuccess")
	public void editGouwucheSuccess(String s) {
		getGouwucgeData();
	}

	private void initTitleBar() {
		btn_back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				EventBus.getDefault().post("", "goFristPage");
			}
		});
	}

	private void initEmptyView(View view) {
		emptyView = view.findViewById(R.id.llyt_emptyview);
		gridview = (NoScrollGridView) view.findViewById(R.id.gridview);
		gridview.setOnItemClickListener(new GridItemClickImpl());
		adapter_empty = new Adapter_Tuijians(getActivity());
		gridview.setAdapter(adapter_empty);
	}

	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		super.setUserVisibleHint(isVisibleToUser);
		init(isVisibleToUser);
	}
	

	private void init(boolean isVisibleToUser) {
		if (isVisibleToUser) {
			if (SessionUtils.checkLogin(getActivity())) {
				emptyView.setVisibility(View.GONE);
				llyt_bottom.setVisibility(View.VISIBLE);
				listview.setVisibility(View.VISIBLE);
				getGouwucgeData();
			} else {
				emptyView.setVisibility(View.VISIBLE);
				llyt_bottom.setVisibility(View.GONE);
				listview.setVisibility(View.GONE);
				getTuijianData();
			}
		}
	}

	/**
	 * 获取推荐
	 */
	private void getTuijianData() {
		Map<String, String> map = HttpUtil.getParams(HttpConst.FRIST_KEY, "cart", HttpConst.SECOND_KEY, "cart");
		Http.getInstant().sendRequest(getActivity(), map, new HttpListener() {

			@Override
			public void onHttpSuccess(String result) {
				JSONObject jsonObject = JSON.parseObject(result);
				jsonObject = jsonObject.getJSONObject("retval");
				List<TuijianGoods> goods = JSON.parseArray(jsonObject.getString("goods_data"), TuijianGoods.class);
				adapter_empty.clear();
				adapter_empty.addAll(goods);
			}

			@Override
			public void onHttpError(String error) {
			}
		});
	}

	private class GridItemClickImpl implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			SkipUtils.seeDetail(getActivity(), adapter_empty.getItem(position).goods_id, adapter_empty.getItem(position).default_image);
		}

	}

	private void getGouwucgeData() {
		Map<String, String> map = HttpUtil.getParams(HttpConst.FRIST_KEY, "cart");
		Http.getInstant().sendRequest(getActivity(), map, new HttpListener() {

			@Override
			public void onHttpSuccess(String result) {
				JSONObject jsonObject = JSON.parseObject(result);
				JSONArray array;
				try {
					array = jsonObject.getJSONArray("retval");
				} catch (Exception e) {
					emptyView.setVisibility(View.VISIBLE);
					llyt_bottom.setVisibility(View.GONE);
					listview.setVisibility(View.GONE);
					getTuijianData();
					return;
				}
				emptyView.setVisibility(View.GONE);
				llyt_bottom.setVisibility(View.VISIBLE);
				listview.setVisibility(View.VISIBLE);
				List<GouwucheList> lists = new ArrayList<GouwucheList>();
				for (int i = 0; i < array.size(); i++) {
					JSONObject object = array.getJSONObject(i);
					GouwucheList gouwucheList = new GouwucheList();
					gouwucheList.store_name = object.getString("store_name");
					gouwucheList.amount = object.getFloatValue("amount");
					gouwucheList.quantity = object.getIntValue("quantity");
					gouwucheList.kinds = object.getIntValue("kinds");
					List<GouwucgeGoods> goodsss = new ArrayList<GouwucgeGoods>();
					JSONArray jsonArray = object.getJSONArray("goods");
					for (int j = 0; j < jsonArray.size(); j++) {
						JSONObject goosObject = jsonArray.getJSONObject(j);
						GouwucgeGoods goods = new GouwucgeGoods();
						goods.rec_id = goosObject.getString("rec_id");
						goods.user_id = goosObject.getString("user_id");
						goods.session_id = goosObject.getString("session_id");
						goods.store_id = goosObject.getString("store_id");
						goods.goods_id = goosObject.getString("goods_id");
						goods.goods_name = goosObject.getString("goods_name");
						goods.spec_id = goosObject.getString("spec_id");
						goods.price = goosObject.getString("price");
						goods.quantity = goosObject.getIntValue("quantity");
						goods.goods_image = goosObject.getString("goods_image");
						goods.group_id = goosObject.getString("group_id");
						goods.old_price = goosObject.getString("old_price");
						goods.store_name = goosObject.getString("store_name");
						goods.subtotal = goosObject.getFloatValue("subtotal");
						goods.is_collect = goosObject.getIntValue("is_collect");
						goods.price_intervals_count = goosObject.getIntValue("price_intervals_count");
						goods.indemnity = goosObject.getBooleanValue("indemnity");
						goods.stock = goosObject.getIntValue("stock");
						List<Gouwuche_specification> specifications = new ArrayList<Gouwuche_specification>();
						JSONArray specificationArray = goosObject.getJSONArray("specification");
						if (specificationArray != null) {
							for (int k = 0; k < specificationArray.size(); k++) {
								JSONObject specificationObject = specificationArray.getJSONObject(k);
								Gouwuche_specification specification = new Gouwuche_specification();
								specification.spec_id = specificationObject.getString("spec_id");
								specification.spec_1 = specificationObject.getString("spec_1");
								specification.price = specificationObject.getFloatValue("price");
								specification.spec = JSON.parseArray(specificationObject.getString("spec"),
										Gouwuche_spec.class);
								specifications.add(specification);
							}
						}
						goods.specification = specifications;
						if (goosObject.getString("quantitydesc") != null
								&& goosObject.getString("quantitydesc").equals("null") == false
								&& goosObject.getString("quantitydesc").equals("") == false) {
							goods.quantitydesc = JSON.parseArray(goosObject.getString("quantitydesc"), String.class);
						}

						goods.price_intervals = JSON.parseArray(goosObject.getString("price_intervals"),
								Detailprice_intervals.class);
						goodsss.add(goods);
					}
					gouwucheList.goods = goodsss;
					lists.add(gouwucheList);
				}
				m_Gouwuche_Adapter = new Adapter_Gouwuche(getActivity(), lists, tv_price, btn_jiesuan);
				listview.setAdapter(m_Gouwuche_Adapter);
				// 结束
//				m_GouwucheList.clear();
//				m_GouwucheList.addAll(lists);
//				LogUtil.e(m_GouwucheList.get(0).goods.size()+"---------------------");
//				m_Gouwuche_Adapter.notifyDataSetChanged();
				for (int i = 0; i < lists.size(); i++) {
					listview.expandGroup(i);
				}
				showPrice(true);
			}

			@Override
			public void onHttpError(String error) {
			}
		});
	}

	@Override
	public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
		return true;
	}

	@Override
	public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
		return true;
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		showPrice(isChecked);
	}

	private void showPrice(boolean isChecked) {
		if(!isChecked){
			btn_jiesuan.setEnabled(false);
		}else{
			btn_jiesuan.setEnabled(true);
		}
		double price = 0;
		for (GouwucheList list : m_Gouwuche_Adapter.getList()) {
			List<GouwucgeGoods> goods = list.goods;
			for (GouwucgeGoods gouwucgeGoods : goods) {
				gouwucgeGoods.isSelect = isChecked;
				if (isChecked) {
					price += gouwucgeGoods.subtotal;
				}
			}
		}
		m_Gouwuche_Adapter.notifyDataSetChanged();
		tv_price.setText("合计（不含运费）: ￥" + Utils.get2point(price));
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_jiesuan:
			StringBuffer store_id_Buffer = new StringBuffer();
			StringBuffer rec_id_Buffer = new StringBuffer();
			StringBuffer id_Buffer = new StringBuffer();
			for (GouwucheList data : m_Gouwuche_Adapter.getList()) {
				List<GouwucgeGoods> goods = data.goods;
				boolean isAppendStore = false;
				for (GouwucgeGoods g : goods) {
					if(g.isSelect == false)continue;
					if(!isAppendStore){
						store_id_Buffer.append(g.store_id);
						store_id_Buffer.append(",");
						isAppendStore = true;
					}
					rec_id_Buffer.append(g.rec_id);
					rec_id_Buffer.append(",");

					id_Buffer.append(g.goods_id);
					id_Buffer.append(",");
				}
			}
			String store_id = store_id_Buffer.toString().substring(0, store_id_Buffer.toString().length() - 1);
			String rec_id = rec_id_Buffer.toString().substring(0, rec_id_Buffer.toString().length() - 1);
			String id = id_Buffer.toString().substring(0, id_Buffer.toString().length() - 1);
			Intent intent = new Intent(getActivity(), Act_Jiesuan.class);
			intent.putExtra("store_id", store_id);
			intent.putExtra("rec_id", rec_id);
			intent.putExtra("id", id);
			startActivity(intent);
			break;
			case R.id.tv_kefu:
				SkipUtils.toChat(getActivity(), null);
				break;
		}
	}

}
